<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="16" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="文件状态" prop="mQaResult">
            <el-select v-model="queryParams.mQaResult" type="mQaResult" placeholder="请选择验收状态" clearable>
              <el-option value="通过" />
              <el-option value="驳回" />
              <el-option value="挂起" />
            </el-select>
          </el-form-item>
          <el-form-item label="文件名" prop="fileId">
            <el-input v-model="queryParams.fileId" type="fileId" placeholder="请输入文件名称" clearable size="small" />
          </el-form-item>
          <el-form-item label="TrackId" prop="trackId">
            <el-input v-model="queryParams.trackId" type="trackId" placeholder="请输入TrackId" clearable size="small" />
          </el-form-item>
          <!--el-form-item label="批注" prop="remark">
            <el-checkbox v-model="queryParams.remark">有批注</el-checkbox>
          </el-form-item-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="resultList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" type="index" align="center" width="60">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="文件名" align="center" width="200px" prop="fileId" :formatter="fileIdFormatter" />
          <el-table-column v-if="!checkrole(['qa'])" label="标注员" prop="updateBy" align="center" width="100">
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime" width="160" />
          <el-table-column label="文件状态" align="center" prop="mQaResult" :formatter="mQaResultFormatter" />
          <!--el-table-column label="二维页面" align="center" prop="mQaResult" :formatter="mQaResultFormatter">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="goToTwoDimensional(scope.row)"
              >二维页面</el-button>
            </template>
          </el-table-column-->

          <el-table-column v-if="imgCount === '10'" label="批注" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <span v-if="scope.row.remark == null || scope.row.remark.split(';').length <= 1">
                {{ scope.row.remark ? scope.row.remark : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="onlineCheck(scope.row)"
                v-hasPermi="['mark:qaresult:edit']"
                >查看</el-button
              >
              <el-button
                v-if="checkrole(['admin'])"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['mark:qaresult:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
          :currentPageChange="currentPageChange"
        />
      </el-col>
      <el-col :span="8" :xs="24">
        <el-row>
          <div>
            <pie-chart :statisticData="statistics" height="350px" />
          </div>
        </el-row>
        <el-row>
          <div>
            <el-form :inline="true" label-width="90px">
              <el-form-item style="display: table-cell; width: 100%; text-align: center">
                <span v-if="statisticMark.rectCount > 0">二维矩形框：{{ statisticMark.rectCount }}</span>
                <span v-if="statisticMark.boxCount > 0">二维立体框：{{ statisticMark.boxCount }}</span>
                <span v-if="statisticMark.lineCount > 0">二维折线：{{ statisticMark.lineCount }}</span>
                <span v-if="statisticMark.polyCount > 0">二维分割：{{ statisticMark.polyCount }}</span>
                <span v-if="statisticMark.point1Count > 0">二维单点：{{ statisticMark.point1Count }}</span>
                <span v-if="statisticMark.rectPoint1Count > 0">二维框带点：{{ statisticMark.rectPoint1Count }}</span>
                <span v-if="statisticMark.cubeCount > 0">三维立体框：{{ statisticMark.cubeCount }}</span>
                <span v-if="statisticMark.splitCount > 0">三维分割：{{ statisticMark.splitCount }}</span>
                <span v-if="statisticMark.otherCount > 0">其他：{{ statisticMark.otherCount }}</span>
              </el-form-item>
            </el-form>
            <pie-mark-chart :statisticMarkData="statisticMark" height="350px" />
          </div>
        </el-row>
      </el-col>
    </el-row>

    <!-- 新建抽检任务对话框对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="抽检名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入抽检任务名称" />
        </el-form-item>
        <el-form-item label="记录占比（%）" prop="percent">
          <el-input v-model="form.percent" placeholder="请输入抽检记录占总数的百分比" />
        </el-form-item>
        <el-form-item label="开始位置" prop="startNum">
          <el-input v-model="form.startNum" placeholder="请输入抽检的开始位置" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog append-to-body :visible.sync="showElementsRemarkDialog" width="300px">
      <el-form>
        <el-form-item v-for="dict in elementsRemark" :key="dict.value" :label="dict.name" :value="dict.value">
          {{ dict.value }}
        </el-form-item>
      </el-form>
    </el-dialog>
    <RemarkList ref="remarkList" :task-id="queryParams.taskId" />
  </div>
</template>

<script>
import PieChart from '../../dashboard/StatisticChart'
import PieMarkChart from '../../dashboard/StatisticMarkChart'
import { listResult, getResult, delResult, exportResult } from '@/api/mark/qaresult'
import { taskStatistic } from '@/api/mark/task'
import { addQaTask, getQaTask } from '@/api/mark/qaTask'
import { pointsCloudDetails, imageFile, pcdBlob } from '@/api/mark/onlineCheck'
import { checkRole } from '@/utils/permission'
import permission from '@/directive/permission/index.js'
import RemarkList from '../editor/components/RemarkList'
import { getReport } from '@/api/mark/report'

export default {
  name: 'Result',
  components: {
    PieChart,
    PieMarkChart,
    RemarkList,
  },
  watch: {
    $route(route) {
      if (route.name === 'Result') {
        this.getList()
      }
    },
  },
  directives: { permission },
  data() {
    return {
      imgCount: 0,
      markTypeOptions: [],
      statistics: null,
      statisticMark: {
        rectCount: null,
        boxCount: null,
        cubeCount: null,
        remarkCount: null,
        rightCount: null,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 质检结果记录表格数据
      resultList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: this.$store.getters.mQaResultcurrentIndex
          ? Math.ceil((Number(this.$store.getters.mQaResultcurrentIndex) + 1) / 10)
          : 1,
        pageSize: 10,
        taskId: null,
        fileId: undefined,
        trackId: undefined,
        mQaResult: undefined,
        remark: false,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      showElementsRemarkDialog: false,
      elementsRemark: [],
      taskInstance: null,
    }
  },
  created() {
    // this.removeAnnotationCache("MA:");
  },
  mounted() {
    this.getList()
    this.getDicts('mark_type').then((response) => {
      this.markTypeOptions = response.data
    })
    taskStatistic(this.$route.query.taskId).then((response) => {
      this.statistics = response.data
    })
    getReport(this.$route.query.taskId).then((response) => {
      let remarkCount = response.remarkCount
      this.statisticMark = {
        rectCount: response.data.rectCount,
        boxCount: response.data.boxCount,
        lineCount: response.data.lineCount,
        polyCount: response.data.polyCount,
        point1Count: response.data.point1Count,
        rectPoint1Count: response.data.rectPoint1Count,
        cubeCount: response.data.cubeCount,
        splitCount: response.data.splitCount,
        otherCount: response.data.otherCount,
        remarkCount: remarkCount,
        rightCount:
          response.data.rectCount +
          response.data.boxCount +
          response.data.lineCount +
          response.data.polyCount +
          response.data.point1Count +
          response.data.rectPoint1Count +
          response.data.cubeCount +
          response.data.splitCount +
          response.data.otherCount -
          remarkCount,
      }
    })
    getQaTask(this.$route.query.taskId).then((response) => {
      this.taskInstance = response.data
    })
  },
  methods: {
    checkrole(role) {
      return checkRole(role)
    },
    markTypeFormat(row, column) {
      return this.selectDictLabel(this.markTypeOptions, row.markType)
    },
    /** 查询质检结果记录列表 */
    getList() {
      this.loading = true
      this.queryParams.taskId = this.$route.query.taskId
      this.queryParams.pageNum = Number(this.$route.query.pageNum) || 1
      if (this.$store.getters.mQaResultcurrentIndex) {
        this.queryParams.pageNum = Math.ceil(
          (Number(this.$store.getters.mQaResultcurrentIndex) + 1) / this.queryParams.pageSize
        )
        this.currentPageChange(this.queryParams.pageNum)
        this.$store.dispatch('mqaResultCurrentIndexCached', null)
      }
      this.cacheBlob(this.queryParams)
    },
    cacheBlob(queryParams) {
      listResult(queryParams).then((response) => {
        this.resultList = response.rows
        this.total = response.total
        this.loading = false
        getQaTask(queryParams.taskId).then((response) => {
          this.$store.state.markData.markAnnotations['QaTask:' + queryParams.taskId] = response
          this.getDicts(response.data.markAttributes).then((res1) => {
            let attributeNames = res1.data
            this.$setItem(response.data.markAttributes, attributeNames)
          })
          this.getDicts(response.data.markAttributes + '_colors').then((res1) => {
            let colorNames = res1.data
            this.saveToCacheDB(response.data.markAttributes + '_colors', colorNames)
          })
          this.imgCount = response.data.markType
          for (let i = 0; i < Math.min(this.resultList.length, 7); i++) {
            let mQaResultId = this.resultList[i].mQaResultId
            pointsCloudDetails(mQaResultId).then((res) => {
              if (res.fileType === 'pcd') {
                pcdBlob(mQaResultId).then((response) => {
                  let blob = new Blob([response.data], { type: 'application/octet-stream' })
                  let annotation = res.annotation
                  let _data = {
                    blob,
                    annotation,
                  }
                  this.saveToCacheDB('MA:' + mQaResultId + '', _data)
                })
              } else if (res.fileType === 'jbin') {
                let pointsCloud = res.pointsCloud
                let annotation = res.annotation
                let _data = {
                  pointsCloud,
                  annotation,
                }
                this.saveToCacheDB('MA:' + mQaResultId + '', _data)
              }
            })
            if (this.imgCount === '9' || this.imgCount === '10') {
              continue
            } else if (this.imgCount === '1') {
              imageFile(mQaResultId, 0).then((response) => {
                let imageSrc = response.imageSrc
                let annotation = response.annotation
                let _data = {
                  imageSrc,
                  annotation,
                }
                // this.saveToCacheDB("MA:" + mQaResultId + ":img", _data);
              })
            } else {
              for (let j = 0; j < this.imgCount; j++) {
                imageFile(mQaResultId, j + 1).then((response) => {
                  let imageSrc = response.imageSrc
                  let annotation = response.annotation
                  let _data = {
                    imageSrc,
                    annotation,
                  }
                  // this.saveToCacheDB("MA:" + mQaResultId + ":img:" + (j+1), _data);
                })
              }
            }
          }
        })
      })
    },
    currentPageChange(page) {
      this.queryParams.pageNum = page
      this.$router.replace({
        path: '/mark/result',
        query: {
          taskId: this.queryParams.taskId,
          pageNum: page,
        },
      })
    },
    saveToCacheDB(_key, _value) {
      this.$setItem(_key, _value, function (err) {
        if (err) {
          console.log('error:')
          console.log(err)
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: undefined,
        fileId: undefined,
        markResultId: undefined,
        markType: undefined,
        mQaResultId: undefined,
        mQaResult: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.mQaResultId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增抽检任务操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加质检结果记录'
    },
    onlineCheck(row) {
      if (row.markType == '0')
        this.$router.push({
          path: '/mark/pointCloudSplit',
          query: {
            taskId: row.taskId,
            mQaResultId: row.mQaResultId,
          },
        })
      // else if(row.markType == "10")
      //   this.$router.push({
      //     path: "/mark/markCheck2d",
      //     query: {
      //       "taskId": row.taskId,
      //       "mQaResultId": row.mQaResultId,
      //       "fileId": row.fileId,
      //     }
      //   });
      else
        this.$router.push({
          path: '/mark/editor2d',
          query: {
            taskId: row.taskId,
            mQaResultId: row.mQaResultId,
          },
        })
    },
    goToTwoDimensional(row) {
      this.$router.push({
        path: '/mark/twodimensional',
        query: {
          taskId: row.taskId,
          mQaResultId: row.mQaResultId,
          fileId: row.fileId,
        },
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const mQaResultId = row.mQaResultId || this.ids
      getResult(mQaResultId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改质检结果记录'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.parentId = this.$route.query.taskId
      this.form.taskType = this.form.startNum + ':' + this.form.percent
      addQaTask(this.form).then((response) => {
        if (response.code === 200) {
          this.msgSuccess('新增成功')
          this.open = false
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.replace({
            path: '/mark/editor2d',
            query: {
              taskId: response.qaTask.taskId,
              mQaResultId: null,
            },
          })
        } else {
          this.msgError(response.msg)
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mQaResultIds = row.mQaResultId || this.ids
      this.$confirm('是否确认删除质检结果记录编号为"' + mQaResultIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delResult(mQaResultIds)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有质检结果记录数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportResult(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
        })
        .catch(function () {})
    },
    fileIdFormatter(row, column) {
      let index = row.fileId.lastIndexOf('/')
      return row.fileId.slice(index + 1 - row.fileId.length).replace('.jbin', '.bin')
    },
    markResultIdFormatter(row, column) {
      let index = row.markResultId.lastIndexOf('/')
      return row.markResultId.slice(index + 1 - row.markResultId.length).replace('.jxml', '.xml')
    },
    mQaResultFormatter(row, column) {
      return row.mQaResult ? row.mQaResult : '待验收'
    },
    remarkFormatter(remark) {
      return remark ? remark.split(';')[0] : ''
    },
    viewMarkElementsRemark2(mQaResultId) {
      this.$refs.remarkList.show(mQaResultId)
    },
    viewMarkElementsRemark(remarkStr) {
      let _array = remarkStr.split(';')
      if (_array.length <= 1) return
      this.elementsRemark = []
      for (let i = 1; i < _array.length; i++) {
        let _data = {
          name: _array[i].split(':')[0],
          value: _array[i].split(':')[1],
        }
        this.elementsRemark.push(_data)
      }
      this.showElementsRemarkDialog = true
    },
  },
}
</script>
